package com.second.app.superthread;

import java.util.concurrent.Exchanger;

/**
 * @Author GYZ
 * @Date 2024/1/16
 * <pre>
 *
 * </pre>
 */
public class ExchangerDemo {
}

class Thread0A extends Thread {

    private final Exchanger<String> exchanger;

    public Thread0A(Exchanger<String> exchanger) {
        this.exchanger = exchanger;
    }

    @Override
    public void run() {
        try {
            System.out.println("在线程A中得到线程B的值=" + exchanger.exchange("中国人A"));
            System.out.println("A end!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Thread0B extends Thread {

    private final Exchanger<String> exchanger;

    public Thread0B(Exchanger<String> exchanger) {
        this.exchanger = exchanger;
    }

    @Override
    public void run() {
        try {
            System.out.println("在线程B中得到线程A的值=" + exchanger.exchange("中国人B"));
            System.out.println("A end!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class DemoRun {
    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();
        Thread0A thread0A = new Thread0A(exchanger);
        Thread0B thread0B = new Thread0B(exchanger);
        thread0A.start();
        thread0B.start();
    }
}
